package com.gitee.srurl.core.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gitee.srurl.core.api.impl.disable.BlacklistDisabledStrategy;
import com.gitee.srurl.core.domain.SucBlacklistDomain;
import com.gitee.srurl.core.exception.ServiceException;
import com.gitee.srurl.core.mapper.SucBlacklistMapper;
import com.gitee.srurl.core.service.ISucBlacklistService;
import com.gitee.srurl.core.util.PageQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author zxw
 * @date 2023/4/27 22:01
 */
@Service
public class SucBlacklistServiceImpl extends ServiceImpl<SucBlacklistMapper, SucBlacklistDomain> implements ISucBlacklistService {

    @Override
    public IPage<SucBlacklistDomain> getList(PageQuery pageQuery, SucBlacklistDomain blacklistDomain) {

        LambdaQueryWrapper<SucBlacklistDomain> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(blacklistDomain.getHost()), SucBlacklistDomain::getHost, blacklistDomain.getHost())
                .eq(StrUtil.isNotBlank(blacklistDomain.getStatus()), SucBlacklistDomain::getStatus, blacklistDomain.getStatus());

        return this.page(pageQuery.build(), queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBlacklist(SucBlacklistDomain blacklistDomain) {

        SucBlacklistDomain historyBlacklistDomain = this.getById(blacklistDomain.getId());
        if (historyBlacklistDomain == null) {
            throw new ServiceException("未查询到对用的黑名单信息！");
        }
        historyBlacklistDomain.setHost(blacklistDomain.getHost());
        historyBlacklistDomain.setStatus(blacklistDomain.getStatus());

        this.updateById(historyBlacklistDomain);
        boolean disable = StrUtil.equals(blacklistDomain.getStatus(), "0");
        BlacklistDisabledStrategy.updateCache(blacklistDomain.getHost(), disable);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(SucBlacklistDomain blacklistDomain) {

        blacklistDomain.setId(null);
        this.save(blacklistDomain);
        boolean disable = StrUtil.equals(blacklistDomain.getStatus(), "0");
        BlacklistDisabledStrategy.updateCache(blacklistDomain.getHost(), disable);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {

        SucBlacklistDomain historyBlacklistDomain = this.getById(id);
        if (historyBlacklistDomain == null) {
            throw new ServiceException("未查询到对用的黑名单信息！");
        }

        this.removeById(id);
        BlacklistDisabledStrategy.updateCache(historyBlacklistDomain.getHost(), false);
    }
}
